<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查询</title>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            font-size: 14px;
            background-color: #f4f4f4;
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            max-width: 800px;
            margin: 20px auto;
        }
        nav {
            margin-bottom: 20px;
            text-align: center;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, select, button {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        button {
            background-color: #007BFF;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
        }
        .details-button {
            display: none;
            margin-left: 10px;
        }
        .table-row:hover .details-button {
            display: inline-block;
        }
        .select2-container--default .select2-selection--single {
            height: 38px;
            padding: 5px 10px;
            display: flex;
            align-items: center;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: normal;
        }
        .select2-container .select2-search--inline .select2-search__field {
            width: 100% !important;
        }
        #backtestModal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border: 1px solid #ddd;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: none;
        }
    </style>
</head>
<body>
<h1>Coin查询回测</h1>
<div class="container">
    <nav>
        <button onclick="getQuote('binance')">币安接口K线查询</button>
        <button onclick="getQuote('h2')">h2数据库查询</button>
        <button onclick="downloadCSV()">下载 CSV</button>
        <button onclick="saveCoinQuotes()">保存查询结果</button>
        <button onclick="openBacktestModal()">回测</button>
    </nav>
    <div class="form-group">
        <label for="symbol">币种符号:</label>
        <select id="symbol" class="form-control"></select>
    </div>
    <div class="form-group">
        <label for="interval">时间周期:</label>
        <select id="interval">
            <option value="1m">1 分钟</option>
            <option value="3m">3 分钟</option>
            <option value="5m">5 分钟</option>
            <option value="15m">15 分钟</option>
            <option value="30m">30 分钟</option>
            <option value="1h">1 小时</option>
            <option value="2h">2 小时</option>
            <option value="4h">4 小时</option>
            <option value="6h">6 小时</option>
            <option value="8h">8 小时</option>
            <option value="12h">12 小时</option>
            <option value="1d">1 天</option>
            <option value="3d">3 天</option>
            <option value="1w">1 周</option>
            <option value="1M">1 月</option>
        </select>
    </div>
    <div id="result"></div>
</div>

<!-- 回测模态框 -->
<div id="backtestModal">
    <label for="backtestModel">选择回测模型:</label>
    <select id="backtestModel">
        <option value="model1">模型1</option>
        <option value="model2">模型2</option>
        <option value="model3">模型3</option>
        <option value="model4">模型4</option>
        <option value="model5">模型5</option>
        <option value="model6">模型6</option>
        <!-- 添加更多模型选项 -->
    </select>
    <button onclick="performBacktest()">确定</button>
    <button onclick="closeBacktestModal()">取消</button>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    let resultData = [];

    function getQuote(queryMethod) {
        var symbol = document.getElementById("symbol").value;
        var interval = document.getElementById("interval").value;
        var url = "/api/quotes?symbol=" + symbol + "&interval=" + interval+"&queryMethod="+queryMethod;
        $.get(url, function(response) {
            if(response.success){
                resultData = response.data;
                displayResult(response.data);
                document.getElementById("symbol").value = symbol;
                document.getElementById("interval").value = interval;
            } else {
                console.error("请求失败:", response.message);
                alert("请求失败");
            }
        }).fail(function(xhr, status, error) {
            console.error("请求失败:", status, error);
            alert("请求失败，请检查控制台以获取更多信息");
        });
    }

    function saveCoinQuotes(){
        var symbol = document.getElementById("symbol").value;
        var interval = document.getElementById("interval").value;
        var url = "/api/saveCoinQuotes";
        var data = {
            symbol: symbol,
            interval: interval
        };

        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function(response) {
                if (response.success) {
                    console.log("请求成功:", response.message);
                    alert("保存查询成功");
                } else {
                    console.error("请求失败:", response.message);
                    alert("保存查询失败");
                }
            },
            error: function(xhr, status, error) {
                console.error("请求失败:", status, error);
                alert("请求失败，请检查控制台以获取更多信息");
            }
        });
    }

    function displayResult(data) {
        debugger;
        var symbol = document.getElementById("symbol").value;
        var interval = document.getElementById("interval").value;
        let resultDiv = document.getElementById("result");
        resultDiv.innerHTML = "";
        let table = document.createElement("table");
        let header = table.createTHead();
        let headerRow = header.insertRow(0);
        let headers = ["选择", "序号", "开盘时间", "开盘价", "最高价", "最低价", "收盘价", "交易量", "收盘时间", "成交额", "成交笔数", "主动买入成交量", "主动买入成交额", "操作"];
        headers.forEach((header, index) => {
            let cell = headerRow.insertCell(index);
            cell.innerHTML = header;
        });
        let tbody = table.createTBody();
        data.sort((a, b) => new Date(b[0]) - new Date(a[0]));
        data.forEach((row, index) => {
            let rowElement = tbody.insertRow();
            let checkboxCell = rowElement.insertCell(0);
            let checkbox = document.createElement("input");
            checkbox.type = "checkbox";
            var uniqueValue = symbol + "-" + interval + "-" + row[0] + "-" + row[6];
            checkbox.value = uniqueValue;
            checkboxCell.appendChild(checkbox);
            rowElement.insertCell(1).innerHTML = uniqueValue;
            rowElement.insertCell(2).innerHTML = new Date(row[0]).toLocaleString();
            rowElement.insertCell(3).innerHTML = row[1];
            rowElement.insertCell(4).innerHTML = row[2];
            rowElement.insertCell(5).innerHTML = row[3];
            rowElement.insertCell(6).innerHTML = row[4];
            rowElement.insertCell(7).innerHTML = row[5];
            rowElement.insertCell(8).innerHTML = new Date(row[6]).toLocaleString();
            rowElement.insertCell(9).innerHTML = row[7];
            rowElement.insertCell(10).innerHTML = row[8];
            rowElement.insertCell(11).innerHTML = row[9];
            rowElement.insertCell(12).innerHTML = row[10];

            // 添加查看预测明细按钮
            let actionCell = rowElement.insertCell(13);
            let detailButton = document.createElement("button");
            detailButton.innerHTML = "查看预测明细";
            detailButton.onclick = function () {
                viewPredictionDetails(uniqueValue);
            };
            actionCell.appendChild(detailButton);
        });
        resultDiv.appendChild(table);
    }

    function downloadCSV() {
        if (resultData.length === 0) {
            alert("没有数据可供下载");
            return;
        }

        let csvContent = "data:text/csv;charset=utf-8,";
        csvContent += "开盘时间,开盘价,最高价,最低价,收盘价,交易量,收盘时间,成交额,成交笔数,主动买入成交量,主动买入成交额\n";
        resultData.sort((a, b) => new Date(b[0]) - new Date(a[0]));
        resultData.forEach(row => {
            let rowString = [
                new Date(row[0]).toLocaleString(),
                row[1],
                row[2],
                row[3],
                row[4],
                row[5],
                new Date(row[6]).toLocaleString(),
                row[7],
                row[8],
                row[9],
                row[10]
            ].join(",");
            csvContent += rowString + "\n";
        });

        let encodedUri = encodeURI(csvContent);
        let link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "quote_data.csv");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    function openBacktestModal() {
        debugger;
        if(!isAnyRowSelected()){
            alert("请至少选择一个序号点进行回测");
            return;
        }
        document.getElementById("backtestModal").style.display = "block";
    }
    function isAnyRowSelected() {
        let checkboxes = document.querySelectorAll("#result input[type='checkbox']");
        if (checkboxes.length === 0) {
            return false;
        }
        for (let checkbox of checkboxes) {
            if (checkbox.checked) {
                return true;
            }
        }
        return false;
    }

    function closeBacktestModal() {
        document.getElementById("backtestModal").style.display = "none";
    }

    function performBacktest() {
        debugger;
        let selectedRows = [];
        let checkboxes = document.querySelectorAll("#result table tbody input[type='checkbox']:checked");
        checkboxes.forEach(checkbox => {
            selectedRows.push(checkbox.value);
        });

        if (selectedRows.length === 0) {
            alert("请选择至少一个序号进行回测");
            return;
        }

        let backtestModel = document.getElementById("backtestModel").value;
        let url = "/api/backtest";
        let data = {
            model: backtestModel,
            selectedData: selectedRows
        };

        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function(response) {
                if (response.success) {
                    console.log("回测成功:", response.message);
                    alert("回测成功");
                    closeBacktestModal();
                } else {
                    console.error("回测失败:", response.message);
                    alert("回测失败");
                }
            },
            error: function(xhr, status, error) {
                console.error("回测请求失败:", status, error);
                alert("回测请求失败，请检查控制台以获取更多信息");
            }
        });
    }


    $(document).ready(function() {
        $('#symbol').select2({
            placeholder: '选择币种符号',
            allowClear: true,
            width: '100%' // 确保 select2 的宽度与父元素一致
        });

        $.ajax({
            url: '/api/getUsdtContracts',
            method: 'GET',
            success: function(response) {
                if(response.success){
                    var symbolSelect = $('#symbol');
                    symbolSelect.empty(); // 清空现有选项
                    $.each(response.data, function(index, symbol) {
                        symbolSelect.append($('<option>', {
                            value: symbol,
                            text: symbol
                        }));
                    });
                    $('#symbol').trigger('change'); // 更新 select2
                } else {
                    console.error('获取币种符号列表失败:', response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error('请求失败:', status, error);
                alert('请求失败，请检查控制台以获取更多信息');
            }
        });
    });


    function viewPredictionDetails(row) {
        var url = "/api/predictDetails";
        var params = {
            predictUniqueTag: row
        };
        var query = Object.keys(params)
            .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
            .join('&');
        window.location.href = url + '?' + query;
    }
</script>
</body>
</html>
